package com.mytest.web;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.lang.reflect.Modifier;
import java.util.Set;

public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        if (set != null) {
            for (Class<?> waiClass : set) {
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        MyWebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        //扫描找到onStartup重写的类，并调用
                        //创建MyWebApplicationInitializer，并调用重写后的onStartupt方法
                        MyWebApplicationInitializer myWebApplicationInitializer = (MyWebApplicationInitializer) waiClass.newInstance();
                        myWebApplicationInitializer.onStartup(servletContext);
                    } catch (Throwable e) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", e);
                    }
                }
            }
        }
    }
}
